// pages/productDetails/productDetails.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    productDetail:{},
    currentData:{},
    currentNum:1,
    showModal: false,
    showAuthPopup: false,
    modalAnimation: null,
    maskAnimation: null
  },

  //加入购物车
  addCar: function(e) {
    let productId=e.currentTarget.dataset.id;
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/addBuyCar",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:_this.data.phone,
        productId:productId,
        buyNum:_this.data.currentNum
      },
      dataType:"json",
      complete:function(result) {
        _this.hideModal();
        wx.showToast({
          title: '加入成功',
          image: '/images/123.png',
          duration: 2000,
          mask:true
        })
        app.getBuyCarNum();
        console.log(888,result.data.data);
      }
    })
  },
    // 增加数量
    increaseQuantity() {
      if(this.data.currentNum<this.data.currentData.inventory){
        this.data.currentNum++;
        this.setData({
          currentNum:this.data.currentNum
        });
      }
    },
  
    // 减少数量
    decreaseQuantity() {
      if(this.data.currentNum>1){
        this.data.currentNum--;
        this.setData({
          currentNum:this.data.currentNum
        });
      }
    },
        // 2.0打开弹窗
showModal(e) {
  if(this.data.phone){
    this.setUser();
     // 创建动画
      const modalAnimation = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease-out'
      })
      
      const maskAnimation = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease-out'
      })

      // 执行动画
      maskAnimation.opacity(1).step()
      modalAnimation.translateY(0).step()
      this.setData({
        currentData:this.data.productDetail,
        showModal: true,
        modalAnimation: modalAnimation.export(),
        maskAnimation: maskAnimation.export()
      })
  }else{
    this.setData({ showAuthPopup: true });
  }
},

hideModal() {
  const modalAnimation = wx.createAnimation({
    duration: 250,
    timingFunction: 'ease-in'
  })
  
  const maskAnimation = wx.createAnimation({
    duration: 250,
    timingFunction: 'ease-in'
  })

  maskAnimation.opacity(0).step()
  modalAnimation.translateY('100%').step()

  this.setData({
    modalAnimation: modalAnimation.export(),
    maskAnimation: maskAnimation.export()
  })

  // 延迟隐藏保证动画完成
  setTimeout(() => {
    this.setData({ showModal: false })
  }, 250)
},

settlement:function(){
  if(this.data.phone){
    this.setUser();
    const arry = [];
    arry.push(this.data.productDetail);
    const items ={
      totalPrice:this.data.productDetail.price,
      totalOriPrice:this.data.productDetail.orinprice,
      orinDiscount:(this.data.productDetail.orinprice-this.data.productDetail.price).toFixed(2),
      items:[
        {
          buyNum:1,
          discountType:this.data.productDetail.discount_type,
          id: '',
          imgUrl: this.data.productDetail.imgUrl,
          inventory: this.data.productDetail.inventory,
          isSelected:1,
          iscoupon: this.data.productDetail.iscoupon,
          orinprice: this.data.productDetail.orinprice,
          price: this.data.productDetail.price,
          productId: this.data.productDetail.id,
          skuName:this.data.productDetail.skuName,
          state: this.data.productDetail.state,
          type: this.data.productDetail.type,
        }
      ]
    }
    console.log(123,items)
    wx.navigateTo({
      url: '/pages/settlement/settlement?item='+JSON.stringify(items)
    })
  }else{
    this.setData({ showAuthPopup: true });
  }
},
//
jumpCar:function(){
  console.log(23)
  wx.switchTab({
    url: '/pages/equity/equity'
  })
},
jumpHome:function(){
  wx.switchTab({
    url: '/pages/index/index'
  })
},
jumpYd:function(e){
  console.log(66,e.currentTarget.dataset.id)
  wx.navigateTo({
    url: '/pages/ydhf/ydhf?url='+e.currentTarget.dataset.id
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options.id)
    
    //获取商品详情
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/productNew/detailById",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{id:options.id},
      dataType:"json",
      complete:function(result) {
        console.log(1234454,result.data.data[0]);
        if(result.data.data[0].imgDetails){
          if(result.data.data[0].imgDetails.indexOf(',')>0){
            result.data.data[0].imgDetails=result.data.data[0].imgDetails.split(',')
          }else{
            result.data.data[0].imgDetails=[result.data.data[0].imgDetails]
          }
        }
        result.data.data[0].phoneBuyFlag=options.phoneBuyFlag
          _this.setData({
            productDetail:result.data.data[0]
          })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      phone:wx.getStorageSync('phone'),
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onGetPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv } = e.detail;
      wx.login({
        success: res => {
          if (res.code) {
            // 发送 res.code 到后台换取 openid, session_key, unionid
            wx.request({
              url: app.globalData.onlineUrl+"/getUserPhone", // 替换为你的服务器地址
              header:{'content-type': 'application/json'},
              method: 'POST',
              data: {
                code: res.code,
                encryptedData:encryptedData,
                iv:iv,
              },
              success: (response) => {
                console.log(10086,response.data.data.phoneNumber);
                // 存储用户信息
                wx.setStorageSync('phone', response.data.data.phoneNumber);
                wx.setStorageSync('openid', response.data.data.openId);
                this.setUser();
                this.setData(
                  {
                    phone:wx.getStorageSync('phone'),
                    showAuthPopup:false
                  }
                )
              }
            });
          } else {
            console.log('登录失败！' + res.errMsg);
          }
        }
      });
    } else {
      // 用户拒绝授权时的处理（根据合规要求，建议允许用户取消）
      wx.showToast({ 
        title: '需要授权手机号才能使用完整服务', 
        icon: 'none',
        duration: 2000
      });
    }
  },
  setUser:function(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/setUser",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone'),
        openId:wx.getStorageSync('openid')
      },
      dataType:"json",
      complete:function(result) {
        console.log("用户信息更新成功");
      }
    })
  },
  onClosePopup() {
    this.setData({ showAuthPopup: false });
  },
})